package com.bawei.module_live.ui

import androidx.lifecycle.viewModelScope
import com.bawei.lib_mvi.base.BaseViewModel
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.consumeAsFlow

/**
 * 直播间模块 - MVI架构 ViewModel层
 * 
 * ViewModel负责业务逻辑处理，包括：
 * - 处理用户操作意图（Intent）
 * - 管理UI状态（State）
 * - 协调数据仓库（Repository）
 * - 错误处理和状态转换
 * 
 * 作为UI层和数据层之间的桥梁，确保数据流的单向性和可预测性
 */
class LiveViewModel : BaseViewModel<LiveIntent>() {
    
    // ==================== 依赖注入 ====================
    
    /**
     * 数据仓库实例
     */
    private val liveRepository: LiveRepository by lazy { LiveRepository() }
    
    // ==================== 状态管理 ====================
    
    /**
     * UI状态流
     * 使用StateFlow确保状态的一致性和线程安全
     */
    private val _liveState = MutableStateFlow<LiveState>(LiveState.Init)
    val liveState = _liveState.asStateFlow()
    
    // ==================== 意图处理 ====================
    
    /**
     * 处理用户操作意图
     * 根据不同的Intent执行相应的业务逻辑
     */
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect { intent ->
                when (intent) {
                    // 获取直播列表
                    is LiveIntent.FetchLiveListIntent -> {
                        handleFetchLiveListIntent(intent)
                    }
                    
                    // 重置状态
                    is LiveIntent.ResetStateIntent -> {
                        _liveState.value = LiveState.Init
                    }
                    
                    // 获取礼物列表
                    is LiveIntent.FetchGiftListIntent -> {
                        handleFetchGiftListIntent()
                    }
                    
                    // 关注用户
                    is LiveIntent.FocuseUserIntent -> {
                        handleFocuseUserIntent(intent)
                    }
                    
                    // 取消关注用户
                    is LiveIntent.UnFocuseUserIntent -> {
                        handleUnFocuseUserIntent(intent)
                    }
                    
                    // 检查关注状态
                    is LiveIntent.CheckFocuseStatusIntent -> {
                        handleCheckFocuseStatusIntent(intent)
                    }
                    
                    // 获取榜单列表
                    is LiveIntent.FetchOrderHotListIntent -> {
                        handleFetchOrderHotListIntent(intent)
                    }
                    
                    // 获取直播间商品列表
                    is LiveIntent.FetchLiveRoomGoodsIntent -> {
                        handleFetchLiveRoomGoodsIntent(intent)
                    }
                }
            }
        }
    }

    fun sendIntent(intent: LiveIntent) {
        intents.trySend(intent)
    }
    
    // ==================== 直播列表相关方法 ====================
    
    /**
     * 处理获取直播列表意图
     * @param intent 获取直播列表意图
     */
    private fun handleFetchLiveListIntent(intent: LiveIntent.FetchLiveListIntent) {
        _liveState.value = LiveState.Loading
        viewModelScope.launch {
            liveRepository.getLiveList(intent.page, intent.pageSize).collect { responseEntity ->
                if (responseEntity.code == 200 && responseEntity.data != null) {
                    _liveState.value = LiveState.LiveListSuccess(responseEntity.data)
                } else {
                    _liveState.value = LiveState.Error(responseEntity.msg ?: "数据异常")
                }
            }
        }
    }
    
    // ==================== 礼物系统相关方法 ====================
    
    /**
     * 处理获取礼物列表意图
     */
    private fun handleFetchGiftListIntent() {
        _liveState.value = LiveState.Loading
        viewModelScope.launch {
            liveRepository.getGiftList().collect { response ->
                if (response.code == 200 && response.data != null) {
                    _liveState.value = LiveState.GiftListSuccess(response.data)
                } else {
                    _liveState.value = LiveState.Error(response.msg ?: "获取礼物失败")
                }
            }
        }
    }
    
    // ==================== 用户关注相关方法 ====================
    
    /**
     * 处理关注用户意图
     * @param intent 关注用户意图
     */
    private fun handleFocuseUserIntent(intent: LiveIntent.FocuseUserIntent) {
        _liveState.value = LiveState.Loading
        viewModelScope.launch {
            liveRepository.focuseUser(intent.focuseUserid, intent.focusedUserid).collect { response ->
                if (response.code == 200 && response.data == true) {
                    _liveState.value = LiveState.FocuseUserSuccess(true)
                } else {
                    _liveState.value = LiveState.Error(response.msg ?: "关注失败")
                }
            }
        }
    }
    
    /**
     * 处理取消关注用户意图
     * @param intent 取消关注用户意图
     */
    private fun handleUnFocuseUserIntent(intent: LiveIntent.UnFocuseUserIntent) {
        _liveState.value = LiveState.Loading
        viewModelScope.launch {
            liveRepository.unFocuseUser(intent.focuseUserid, intent.focusedUserid).collect { response ->
                if (response.code == 200 && response.data == true) {
                    _liveState.value = LiveState.UnFocuseUserSuccess(true)
                } else {
                    _liveState.value = LiveState.Error(response.msg ?: "取消关注失败")
                }
            }
        }
    }
    
    /**
     * 处理检查关注状态意图
     * @param intent 检查关注状态意图
     */
    private fun handleCheckFocuseStatusIntent(intent: LiveIntent.CheckFocuseStatusIntent) {
        viewModelScope.launch {
            try {
                liveRepository.getFocuseListByUserId(intent.myUserId).collect { response ->
                    if (response.code == 200 && response.data != null) {
                        val isFocuse = response.data.any { it.id == intent.anchorId }
                        _liveState.value = LiveState.FocuseStatus(isFocuse)
                    } else {
                        // 如果接口返回404或数据为空，认为未关注，不弹Toast
                        _liveState.value = LiveState.FocuseStatus(false)
                    }
                }
            } catch (e: Exception) {
                // 只有真正的网络异常才提示
                if (e is retrofit2.HttpException && e.code() == 404) {
                    // 404静默处理，认为未关注
                    _liveState.value = LiveState.FocuseStatus(false)
                } else {
                    _liveState.value = LiveState.Error("网络异常，请稍后重试")
                }
            }
        }
    }
    
    // ==================== 榜单系统相关方法 ====================
    
    /**
     * 处理获取榜单列表意图
     * @param intent 获取榜单列表意图
     */
    private fun handleFetchOrderHotListIntent(intent: LiveIntent.FetchOrderHotListIntent) {
        _liveState.value = LiveState.Loading
        viewModelScope.launch {
            liveRepository.getOrderHortList(intent.type).collect { response ->
                if (response.code == 200 && response.data != null) {
                    _liveState.value = LiveState.OrderHotListSuccess(response.data)
                } else {
                    _liveState.value = LiveState.Error(response.msg ?: "获取榜单失败")
                }
            }
        }
    }
    
    // ==================== 商品系统相关方法 ====================
    
    /**
     * 处理获取直播间商品列表意图
     * @param intent 获取直播间商品列表意图
     */
    private fun handleFetchLiveRoomGoodsIntent(intent: LiveIntent.FetchLiveRoomGoodsIntent) {
        _liveState.value = LiveState.Loading
        viewModelScope.launch {
            liveRepository.getLiveRoomGoods(intent.roomId).collect { response ->
                if (response.code == 200 && response.data != null) {
                    _liveState.value = LiveState.LiveShopListSuccess(response.data.records)
                } else {
                    _liveState.value = LiveState.Error(response.msg ?: "获取商品列表失败")
                }
            }
        }
    }
}